import Vue from 'vue';
import Vuex from 'vuex';
import app from './modules/app';
import API from '../API';
import Cookies from 'js-cookie';
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    roles: ['admin'],
    user: null,
    Locations: []
  },
  mutations: {
    logOut (state) {
      state.user = null;
      state.roles = [];
      window.localStorage.removeItem('TokenID');
    },
    setUser (state, data) {
      state.user = data;
    },
    setUserAndRole (state, data) {
      state.user = data;
    },
    setLocations (state, data) {
      state.Locations = data;
    }
  },
  actions: {
    getuser ({ commit, state }) {
      let pre = new Promise((resolve, reject) => {
        if (state.user !== null && state.user !== '') {
          resolve(state.user);
        } else {
          let ticket = window.localStorage.getItem('TokenID');
          let loginType = window.localStorage.getItem('loginType');

          if (loginType && loginType === 'back' && ticket) {
            API.tookenlogin(ticket).then((res) => {
              let json = res.data;

              if (json.status === '200') {
                let user = json.data;

                window.localStorage.setItem('TokenID', json.data.TokenID);
                window.localStorage.setItem('loginType', 'back');
                commit('setUserAndRole', user);
                resolve(json.data);
              } else {
                window.localStorage.removeItem('loginType');
                reject(new Error('apiError'));
              }
            }).catch(() => {
              window.localStorage.removeItem('loginType');
              reject(new Error('apiError'));
            });
            return;
          }
          let phplogin = Cookies.get('phplogin');

          if (phplogin) {
            API.checklogin({
              phplogin: phplogin
            }).then((res) => {
              let json = res.data;

              if (json.status === '200') {
                let user = json.data;

                window.localStorage.setItem('TokenID', json.data.TokenID);
                window.localStorage.removeItem('loginType');
                // Cookies.set('TokenID',json.data.TokenID,{ expires: 7 });
                commit('setUserAndRole', user);
                resolve(json.data);
              } else {
                reject(new Error('apiError'));
              }
            }).catch(() => {
              reject(new Error('apiError'));
            });
          } else {
            reject(new Error('nophplogin'));
          }
        }
      });

      return pre;
    }

  },
  modules: {
    app
  }
});

export default store;
